package com.hjc.oj.judge;

import cn.hutool.json.JSONUtil;
import com.hjc.oj.common.ErrorCode;
import com.hjc.oj.exception.BusinessException;
import com.hjc.oj.judge.codesandbox.CodeSandBox;
import com.hjc.oj.judge.codesandbox.CodeSandBoxFactory;
import com.hjc.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.hjc.oj.judge.codesandbox.model.ExecuteCodeResponse;
import com.hjc.oj.judge.codesandbox.model.JudgeInfo;
import com.hjc.oj.judge.strategy.JudgeContext;
import com.hjc.oj.model.dto.question.JudgeCase;
import com.hjc.oj.model.entity.Question;
import com.hjc.oj.model.entity.QuestionSubmit;
import com.hjc.oj.model.enums.JudgeInfoMessageEnum;
import com.hjc.oj.model.enums.QuestionSubmitSatatusEnum;
import com.hjc.oj.service.QuestionService;
import com.hjc.oj.service.QuestionSubmitService;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class JudgeServiceImpl implements JudgeService {

    @Value("${codesandbox.type:example}")
    private String type;


    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private JudgeManager judgeManager;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {
        //1.获取题目的信息和题目提交信息，代码、编程语言等
        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"提交信息不存在");
        }
        Question question = questionService.getById(questionSubmit.getQuestionId());
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"题目不存在");
        }
        //2.判断当前题目提交信息的状态 不是非等待状态、即已正在判题中，或者判题结束
        //todo判题条件不明确
        if(questionSubmit.getStatus().equals(QuestionSubmitSatatusEnum.WAITING)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"提交结果判题中");
        }
        //3.更改代码提交状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitSatatusEnum.RUNNING.getValue());
        Boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目状态更新失败");
        }
        //4.调用代码沙箱，获取执行结果
        CodeSandBox codeSandBox = CodeSandBoxFactory.newInstance(type);
        String language = questionSubmit.getLanguage();
        String code = questionSubmit.getCode();
        //获取测试用例
        String judgeCaseStr = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCaseStr, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .inputList(inputList)
                .code(code)
                .language(language)
                .build();
//        System.out.println(executeCodeRequest);
        //远程沙箱执行代码
        ExecuteCodeResponse executeCodeResponse = codeSandBox.executeCode(executeCodeRequest);
        //执行结束
        System.out.println("远程代码执行结束,根据结果判断-------->"+executeCodeResponse.toString());
        //编译失败
        if(executeCodeResponse.getStatus() == 3){
            System.out.println("编译失败");
            questionSubmitUpdate = new QuestionSubmit();
            questionSubmitUpdate.setId(questionSubmitId);
            questionSubmitUpdate.setStatus(3);
            questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(executeCodeResponse.getJudgeInfo()));
            update = questionSubmitService.updateById(questionSubmitUpdate);
            if (!update) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
            }
            QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
            return questionSubmitResult;
        }
        System.out.println("编译成功---------->");


        List<String> outputList = executeCodeResponse.getOutputList();
//        System.out.println(executeCodeResponse);
       // 5.根据沙箱的执行结果，设置题目的判题状态和信息；
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(outputList);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestion(question);
        judgeContext.setQuestionSubmit(questionSubmit);
        


        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);
        System.out.println("判断沙箱输出结果和预期结果"+judgeInfo);
        //放到判题策略类里面、java、不同语言启动沙箱也需要不同时间
//        JudgeInfoMessageEnum judgeInfoMessageEnum = JudgeInfoMessageEnum.WAITING;
//        //逻辑判断
//        //1.输出数量
//        if(outputList.size()!=inputList.size()){
//            judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
//            return null;
//        }
//        //2.每一项输出
//        for(int i = 0; i<judgeCaseList.size();i++){
//            JudgeCase judgeCase = judgeCaseList.get(i);
//            if(!judgeCase.getOutput().equals(outputList.get(i))){
//                judgeInfoMessageEnum = JudgeInfoMessageEnum.WRONG_ANSWER;
//                return null;
//            }
//        }
//        //3.时间限制，空间限制
//        JudgeInfo judgeInfo = executeCodeResponse.getJudgeInfo();
//        Long memory = judgeInfo.getMemory();
//        Long time = judgeInfo.getTime();
//
//        String JudgeConfigStr = question.getJudgeConfig();
//        JudgeConfig judgeConfig = JSONUtil.toBean(JudgeConfigStr, JudgeConfig.class);
//
//        Long maxTimeLimit = judgeConfig.getTimeLimit();
//        Long maxMemoryLimit = judgeConfig.getMemoryLimit();
//
//        if(memory > maxMemoryLimit){
//            judgeInfoMessageEnum = JudgeInfoMessageEnum.TIME_LIMIT_EXCEEDED;
//            return null;
//        }
//        if(time > maxTimeLimit){
//            judgeInfoMessageEnum = JudgeInfoMessageEnum.MEMORY_LIMIT_EXCEEDED;
//            return null;
//        }

        //6.修改数据库中的判题结果
        //6.更改数据库内的信息
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        if(JudgeInfoMessageEnum.ACCEPTED.getValue().equals(judgeInfo.getMessage())){
            questionSubmitUpdate.setStatus(QuestionSubmitSatatusEnum.SUCCEED.getValue());
        }else{
            questionSubmitUpdate.setStatus(QuestionSubmitSatatusEnum.FAILED.getValue());
        }

        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        update = questionSubmitService.updateById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "题目状态更新错误");
        }
        QuestionSubmit questionSubmitResult = questionSubmitService.getById(questionSubmitId);
        return questionSubmitResult;

    }
}
